<?php
/**
 *@desc 登录操作Model
 *@author fudaoji
 */

class LoginModel extends Orm_Base{
	public $table = 'auth_user';
	public $pk = 'code';
	public $field = array(
		'id'  => array('type' => "int(10)", 'comment' => '主键'),
		'code' => array('type' => "char(11)", 'comment' => '帐号'),
		'mid' => array('type' => "int(2)", 'comment' => '权限值'),
		'salt' => array('type' => "int(4)", 'comment' => '加密参数'),
		'password' => array('type' => "char(32)", 'comment' => '用户密码'),
	);

	/**
	 * @desc登录函数
	 *@param string $uid 帐号
	 *@param string $pwd 密码
	 *@param int $role 身份 
	 */
	public function login($code, $pwd, $role){
		if (!$user=$this->where("code='$code'")->fRow()) return 3;
		if($user['password']!=$this->password($user['salt'],$pwd)) return 4;
		if($user['mid']!=$role) return 5;
		($role==3) && $this->table('student');
		($role==2) && $this->table('teacher');
		$userInfo = $this->fRow($user['id']);
		$_SESSION['userName']  = $userInfo['name'];
		$_SESSION['code']   = $code;
		$_SESSION['mid']   = $role;
		return 0;
	}

	/**
	 * @desc重置密码函数
	 *@param array $pwdArr 密码数组(包括原密码，新密码，重输密码)
	 */
	public function resetPassword($pwdArr=array(), $self=true){
		if(!$user=$this->fRow($pwdArr['uid'])) return 3;
		if ($self==true && $this->password($user['salt'],$pwdArr['oldPwd'])!=$user['password']) {
			return 6;
		}
		
		if($pwdArr['newPwd']!=$pwdArr['confirmPwd']) return 7;
		//加密得到新密码
		$salt   = $this->salt();
		$newPwd = $this->password($salt, $pwdArr['newPwd']);
		//更新密码
		if($this->update(array('uid'=>$user['uid'],'salt'=>$salt, 'password'=>$newPwd))) return 0;
	}

	/**
	 * @desc判断用户是否存在,不存在的话就添加用户
	 * @param array $userInfo 用户信息
	 */
	public function insertUser($userInfo=array()){
		if($this->fRow($userInfo['uid'])) return 8;
		$salt = $this->salt(); 
		$userInfo['salt']     = $salt;
		$userInfo['password'] = $this->password($salt, $userInfo['password']);
		if($this->insert($userInfo)) return 0;
	}

	/**
	 * @desc更新用户数据
	 * @param array $userInfo 用户信息
	 */
	public function updateUser($userInfo=array()){
		//if($this->fRow($userInfo['uid'])) return 8;
		$salt = $this->salt(); 
		$userInfo['salt']     = $salt;
		$userInfo['password'] = $this->password($salt, $userInfo['password']);
		if($this->update($userInfo)) return 0;
	}

	/**
	 *@desc删除用户
	 *@param string $uid 
	 */
	public function deleteUser($uid=0){
		$this->del($uid);
	}
}